﻿using System.Globalization;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;

namespace AuthClientApi.OAuth
{
    //https://localhost:44338/WeatherForecast
    public class SBlogOAuthHandler : OAuthHandler<SBlogOAuthOptions>
    {
        public SBlogOAuthHandler(IOptionsMonitor<SBlogOAuthOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
        {
        }
        /// <summary>
        ///第一步： 生成跳转第三方登录页面地址
        /// </summary>
        /// <param name="properties"></param>
        /// <param name="redirectUri"></param>
        /// <returns></returns>
        protected override string BuildChallengeUrl(AuthenticationProperties properties, string redirectUri)
        {
            //状态码
            var state = Options.StateDataFormat.Protect(properties);
            var parameters = new Dictionary<string, string>()
            {
                { "client_id", "mvc3" },
                { "redirect_uri", "https://localhost:44338/callback/login/local" },
                { "response_type", "code" },
                { "nonce", "7As19b9qWgpzsC1yXpGHHP3xVHC_LE5ilm8a1OnzyoM" },
                { "code_challenge", "dcNLwXU3mC4ibpdiyDRZbtsvwXFzsoFeHZ6VNbQxKQU" },
                { "code_challenge_method", "S256" }
            };
            if (Options.UsePkce)
            {
                var bytes = new byte[32];
                RandomNumberGenerator.Fill(bytes);
                var codeVerifier = Microsoft.AspNetCore.Authentication.Base64UrlTextEncoder.Encode(bytes);

                // Store this for use during the code redemption.
                properties.Items.Add(OAuthConstants.CodeVerifierKey, codeVerifier);

                var challengeBytes = SHA256.HashData(Encoding.UTF8.GetBytes(codeVerifier));
                var codeChallenge = WebEncoders.Base64UrlEncode(challengeBytes);

                parameters[OAuthConstants.CodeChallengeKey] = codeChallenge;
                parameters[OAuthConstants.CodeChallengeMethodKey] = OAuthConstants.CodeChallengeMethodS256;
            }
            var ret = QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, parameters!);
            //scope 不能被UrlEncode
            string scope= "openid email profile";
            ret += $"&scope={scope}&state={state}";
            return ret;
        }
        /// <summary>
        /// 接收Code
        /// </summary>
        /// <returns></returns>
        //protected override async Task<HandleRequestResult> HandleRemoteAuthenticateAsync()
        //{
        //    IQueryCollection query = Request.Query;
        //    var code = query["code"];
        //    var state = query["state"];


        //}
    }
}
